'''
Created on 2011-07-18

@author: Conan Fan Li
'''
import os
import pickle
import re
import time
import csv


class Matrix(object):
    def __init__(self, filename):
        self.data = []
        f = open(filename)
        reader = csv.reader(f)
        for row in reader:
            self.data.append(map(int, row))
    
    def get(self, a, b):
        return self.data[a][b]
    
    def __repr__(self):
        rv = ''
        for row in self.data:
            for value in row:
                rv += str(value).rjust(5)
            rv += '\n'
        return rv
    
def getDir(path):
    s = os.path.abspath(os.path.dirname(path)) + '/'
    return re.sub(r'\\', '/', s)

        
def saveObj(sch, filename):
    pickle.dump(sch, open(filename, 'wb'))

def loadObj(filename):
    return pickle.load(open(filename, 'rb'))


def isFile(arg):
    return os.path.exists(arg)
    
def toInt(s):
    try:
        return int(s)
    except ValueError:
        return s

def dictStr(d):
    '''
    @param d: the dictionary to be converted to string
    @type d: C{dict}
    @rtype: C{str}
    '''
    assert type(d) == dict, '{} is not a dictionary'.format(d)
    return '{{{pairs}\n}}'.format(pairs=',\n'.join(str((k, d[k])) for k in d))

class Timer(object):
    def __init__(self):
        self._tstart = 0
        self._durations = []
         
    def start(self):
        self._tstart = round(time.clock(), 2)
        
    def pause(self):
        NOW = round(time.clock(), 2)
        start = round(self._tstart, 2)
        self._durations.append((start, NOW, round(NOW - start, 2)))
        self._tstart = round(NOW, 2)
        
    def showAll(self):
        return self._durations
    
    def getSpan(self):
        return self._durations[-1][1]


class Stat(object):
    '''
    A statistic recorder for schedule-flow
    '''
    def __init__(self):
        self.generated = 0
        self.expanded = 0
        self.deleted = 0
        self.pushed = 0
        self.updated = 0
        self.maxFringeLen = 0
    

    def __repr__(self):
        return '''        ********************************************************************
        Statistics:
        ____________________________________________________________________
        Generated  Expanded   Pushed     Updated    Deleted    MaxFringeLen\n
        %-10s %-10s %-10s %-10s %-10s %-10s
        ********************************************************************
        ''' % (self.generated, self.expanded,
               self.pushed, self.updated, self.deleted, self.maxFringeLen)
